package com.guanglan.shrio;

import java.util.ArrayList;
import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.guanglan.domain.SysPermission;
import com.guanglan.domain.SysRole;
import com.guanglan.domain.SysUser;
import com.guanglan.service.SysUserService;


@Component
public class WebShiroRealm extends AuthorizingRealm{
	
	Logger log = LoggerFactory.getLogger(WebShiroRealm.class);
	
	@Autowired
	private WebShiroComponent webShiroRealm;
	@Autowired
	private SysUserService sysUserService;
	
	/**
	 * 授权操作
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {
		String currentUsername = (String)principal.getPrimaryPrincipal();
        List<SysRole> roleList = webShiroRealm.getRoles(currentUsername);
        List<String> roleLists = new ArrayList<String>();
        if(roleList != null && roleList.size() > 0){
        	for(SysRole str : roleList){
        		roleLists.add(str.getRoleName());
        	}
        }
        List<SysPermission> permissionList = webShiroRealm.getPermissions(currentUsername);
        List<String> permissionLists = new ArrayList<String>();
        if(permissionList != null && permissionList.size() > 0){
        	for(SysPermission permissions : permissionList){
        		permissionLists.add(permissions.getPermission());
        	}
        }
        SimpleAuthorizationInfo simpleAuthorInfo = new SimpleAuthorizationInfo();
        simpleAuthorInfo.addRoles(roleLists);
        simpleAuthorInfo.addStringPermissions(permissionLists);
        
		return simpleAuthorInfo;
	}
	
	/**
	 * 认证操作
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
		UsernamePasswordToken token=(UsernamePasswordToken) authenticationToken;
		String userName = token.getUsername();
		SysUser user =  sysUserService.selectByUserName(userName);
		if(user.getIsLock() == 0){
			new LockedAccountException("该账户已被锁定--");
		}
		Object credentials = user.getPassWord();
		ByteSource salt=ByteSource.Util.bytes(String.valueOf(user.getSalt()));
		SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user.getUserName(),credentials,salt,getName());
		this.setSession("currentUser", userName);  
		List<SysPermission> permissionList = webShiroRealm.getPermissions(userName);
		this.setSession("permissionList", permissionList); 
		return authenticationInfo;
	}
	
	/**
	 * 将当前用户存入Session
	 * @param key
	 * @param value
	 */
	private void setSession(Object key, Object value){  
        Subject currentUser = SecurityUtils.getSubject();  
        if(null != currentUser){  
            Session session = currentUser.getSession();  
            if(null != session){  
            	log.info("将当前用户存入Session");
                session.setAttribute(key, value);  
            }  
        }  
    }  
}
